// utils/router.js
// 路由拦截器 - 检查token并自动跳转到登录页

// 不需要登录的页面路径
const whiteList = [
  '/pages/login/login',
  '/pages/loading/loading',
  '/pages/test-router/test-router'
]

// 检查token是否存在且有效
export const checkToken = () => {
  const token = uni.getStorageSync('token')
  return token && token.trim() !== ''
}

// 检查当前页面是否需要登录
export const needAuth = (path) => {
  return !whiteList.includes(path)
}

// 从URL获取当前页面路径
export const getCurrentPathFromUrl = () => {
  // 在H5环境中，可以从location.hash获取路径
  if (typeof window !== 'undefined' && window.location) {
    const hash = window.location.hash
    if (hash) {
      // 移除#号并获取路径
      const path = hash.substring(1)
      console.log('从URL获取的路径:', path)
      return path
    }
  }
  return null
}

// 路由拦截器
export const routerInterceptor = (options) => {
  const { url } = options
  
  // 如果是白名单页面，直接跳转
  if (!needAuth(url)) {
    return true
  }
  
  // 检查token
  if (!checkToken()) {
    // 没有token，跳转到登录页
    uni.showToast({
      title: '请先登录',
      icon: 'none',
      duration: 2000
    })
    
    // 延迟跳转，让用户看到提示
    setTimeout(() => {
      uni.reLaunch({
        url: '/pages/login/login'
      })
    }, 1000)
    
    return false
  }
  
  return true
}

// 页面跳转拦截
export const navigateTo = (options) => {
  if (routerInterceptor(options)) {
    uni.navigateTo(options)
  }
}

// 页面重定向拦截
export const redirectTo = (options) => {
  if (routerInterceptor(options)) {
    uni.redirectTo(options)
  }
}

// 页面重启动拦截
export const reLaunch = (options) => {
  if (routerInterceptor(options)) {
    uni.reLaunch(options)
  }
}

// 页面切换拦截
export const switchTab = (options) => {
  if (routerInterceptor(options)) {
    uni.switchTab(options)
  }
}

// 检查当前页面是否需要登录
export const checkCurrentPageAuth = () => {
  const pages = getCurrentPages()
  console.log('当前页面栈:', pages)
  
  let currentPath = null
  
  // 如果页面栈为空，尝试从URL获取当前路径
  if (pages.length === 0) {
    currentPath = getCurrentPathFromUrl()
    if (!currentPath) {
      // 如果无法获取路径，延迟检查
      setTimeout(() => {
        checkCurrentPageAuth()
      }, 100)
      return true
    }
  } else {
    const currentPage = pages[pages.length - 1]
    currentPath = '/' + currentPage.route
  }
  
  console.log('当前页面路径:', currentPath)
  
  if (needAuth(currentPath) && !checkToken()) {
    console.log('页面需要登录但无token，跳转到登录页')
    uni.showToast({
      title: '请先登录',
      icon: 'none',
      duration: 2000
    })
    
    setTimeout(() => {
      uni.reLaunch({
        url: '/pages/login/login'
      })
    }, 1000)
    
    return false
  }
  
  return true
}

// 初始化路由拦截器
export const initRouterInterceptor = () => {
  console.log('初始化路由拦截器')
  
  // 重写uni的路由方法
  const originalNavigateTo = uni.navigateTo
  const originalRedirectTo = uni.redirectTo
  const originalReLaunch = uni.reLaunch
  const originalSwitchTab = uni.switchTab
  
  uni.navigateTo = (options) => {
    if (routerInterceptor(options)) {
      originalNavigateTo.call(uni, options)
    }
  }
  
  uni.redirectTo = (options) => {
    if (routerInterceptor(options)) {
      originalRedirectTo.call(uni, options)
    }
  }
  
  uni.reLaunch = (options) => {
    if (routerInterceptor(options)) {
      originalReLaunch.call(uni, options)
    }
  }
  
  uni.switchTab = (options) => {
    if (routerInterceptor(options)) {
      originalSwitchTab.call(uni, options)
    }
  }
} 